extends Node2D

@onready var image: AnimatedSprite2D = $image
@onready var layer_0: TileMapLayer = $"../tile_map/layer0"
@onready var layer_1: TileMapLayer = $"../tile_map/layer1"
@onready var bridge_list: Node2D = $bridge_list
@onready var particle: CPUParticles2D = $particle
@onready var sound: AudioStreamPlayer2D = $sound

var mouse_offset=Vector2(16,-48)
var pos_offset=Vector2i(1,0)
enum state{select,build}
var cur_state=state.select
var is_building=false
var movable=true
var pos
var space

func _move():
	space=layer_0.get_used_cells()
	if movable:
		var mouse=get_global_mouse_position()+mouse_offset
		pos=layer_0.local_to_map(mouse)+pos_offset
		self.global_position=layer_0.map_to_local(pos)
	if pos in space:
		image.play("choose")
	else:
		image.play("ban")

func _state_shift():
	if cur_state==state.select:
		cur_state=state.build
		bridge_list.visible=true
		movable=false
	elif cur_state==state.build:
		cur_state=state.select
		bridge_list.visible=false
		movable=true

func _set_bridge(type):
	sound.play()
	layer_1.set_cell(pos,type,Vector2i(0,0))
	layer_0.erase_cell(pos)
	space=layer_0.get_used_cells()
	if particle.emitting:
		particle.emitting=false
	particle.emitting=true

func _interact():
	if not is_building:
		return
	if Input.is_action_just_pressed("select"):
		if cur_state==state.build:
			return
		if pos in space:
			_state_shift()
	elif Input.is_action_just_pressed("return"):
		if cur_state==state.select:
			return
		_state_shift()
	elif Input.is_action_just_pressed("c1"):
		if cur_state==state.select:
			return
		if global.triangle<2 or global.diamond<1 or global.cube<1:
			return
		global.triangle-=2
		global.diamond-=1
		global.cube-=1
		_set_bridge(0)
		_state_shift()
	elif Input.is_action_just_pressed("c2"):
		if cur_state==state.select:
			return
		if global.diamond<1:
			return
		global.diamond-=1
		_set_bridge(2)
		_state_shift()
	elif Input.is_action_just_pressed("c3"):
		if cur_state==state.select:
			return
		if global.cube<1:
			return
		global.cube-=1
		_set_bridge(2)
		_state_shift()

func _physics_process(delta: float) -> void:
	_move()
	_interact()
